// const childProcess = require('child_process')
const childProcess = require('child_process')
const { isArray } = require('../classes/CommitCollection')

function fetchCommand (command, options, handleChunk) {
  return new Promise((resolve, reject) => {
    const sub = childProcess.exec(command, { cwd: options.dir })
    // (command[, args][, options])

    let data = []
    sub.stdout.on('data', function (chunk) {
      // console.log('chunk',JSON.stringify(chunk));
      if(typeof handleChunk === 'function'){
        chunk = handleChunk(chunk)
      }
      if(isArray(chunk)){
        data = data.concat(chunk)
      } else {
        (chunk &&　data.push(chunk))
      }
      console.log(data.length)
      options.setProgress(data.length)
    })
    sub.stdout.on('close', function () {
      options.verbose && options.logger(command)
      resolve(data)
    })
    sub.stderr.on('error', function (err) {
      reject(err)
    })
  })
}

module.exports = fetchCommand
